//
//  YWNoticeManager.m
//  maintain
//
//  Created by Kyo on 16/3/4.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWNoticeManager.h"
#import "YWNoticeDBManager.h"
#import "WMHttpTool.h"
#import "MJExtension.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"

#import "YWDepartment.h"
#import "YWOrganization.h"
#import "YWResourceManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWNotifyManager.h"
#import "YWPatrolPicture.h"

@interface YWNoticeManager ()
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
@end

@implementation YWNoticeManager
YWSingletonM(Manager)

//- (dispatch_queue_t)serialQueue
//{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadTaskserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}

- (BOOL)updateNoticeWithNoticeArray:(NSArray*)notices{
    return [[YWNoticeDBManager shareManager] updateNoticeWithNoticeArray:notices];
}

- (NSArray*)noticesOfTypeWithMeOrOthers:(YWNoticeType)noticeType page:(NSInteger)page{
    return [[YWNoticeDBManager shareManager] noticesOfTypeWithMeOrOthers:noticeType page:page];
}

- (YWNotice*)noticeWithNoticeId:(NSInteger)noticeId{
    return [[YWNoticeDBManager shareManager] noticeWithNoticeId:noticeId];
}

- (BOOL)existNoticeWithNoticeId:(NSInteger)noticeId{
    return [[YWNoticeDBManager shareManager] existNoticeWithNoticeId:noticeId];
}

- (BOOL)deleteNoticeWithNoticeId:(NSInteger)noticeId{
    return [[YWNoticeDBManager shareManager] deleteNoticeWithNoticeId:noticeId];
}

- (BOOL)deletePictureOfNoticeWithNoticeId:(NSInteger)noticeId{
    return [[YWNoticeDBManager shareManager] deletePictureOfNoticeWithNoticeId:noticeId];
}

- (void)requestNoticeListWithPage:(NSInteger)page pageSize:(NSInteger)pageSize withComplete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getNoticeUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* notices = [YWNotice mj_objectArrayWithKeyValuesArray:json];
        
        [[YWNoticeManager shareManager] updateNoticeWithNoticeArray:notices];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)postNoticeWithTitle:(NSString *)title contnet:(NSString *)content departments:(NSArray *)departments pistures:(NSArray *)pictures WithComplete:(void (^)(BOOL))complete{
    if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        if (complete) {
            complete(NO);
        }
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager]
         uploadPatrolPictureToAliyunOSS:pictures
         complete:^(BOOL isError, NSArray* uploadPictures) {
             [self pictureCompleteHandleWithTitle:title contnet:content departments:departments pistures:uploadPictures error:isError WithComplete:^(BOOL success) {
                 if (complete) {
                     complete(success);
                 }
             }];
         }];
    });
}

- (void)pictureCompleteHandleWithTitle:(NSString *)title contnet:(NSString *)content departments:(NSArray *)departments pistures:(NSArray *)pictures error:(BOOL)isError WithComplete:(void (^)(BOOL))complete{
    //[[YWDBTool shareDBTool] updatePatrolPictureWithArray:pictures];
    if (!isError) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {if (complete) {complete(NO);}return;}
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:title?:@"" forKey:@"title"];
        [params setValue:content?:@"" forKey:@"content"];
        [departments enumerateObjectsUsingBlock:^(YWDepartment*  _Nonnull department, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setValue:@(department.departmentId) forKey:[NSString stringWithFormat:@"departmentReceivers[%lu].departmentId",(unsigned long)idx]];
            [params setValue:department.organization.organizationNo forKey:[NSString stringWithFormat:@"organizationReceiver[%lu].organizationNo",(unsigned long)idx]];
        }];
        [pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull pic, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setObject:pic.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].url", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].thumbnailUrl", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].previewUrl", (unsigned long)idx]];
        }];
        YWLog(@"params = %@",params);
        [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getNoticeUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
            YWNotice* notice = [YWNotice mj_objectWithKeyValues:json];
            if (notice) {
                notice.createTime = [[NSDate date] timeIntervalSince1970]*1000;
                [[YWNoticeManager shareManager] updateNoticeWithNoticeArray:@[notice]];
                [[NSNotificationCenter  defaultCenter] postNotificationName:KRefreshPostYWNoticeNotification object:nil];
            }
            if (complete) {
                complete(YES);
            }
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
            }
            if (complete) {
                complete(NO);
            }
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        }];
    }else{
        if (complete) {
            complete(NO);
        }
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
    }
}
- (void)modifyNoticeWithNotice:(YWNotice *)notice needUploadPic:(NSArray *)needUploadPic uploadedPic:(NSArray *)uploadedPic WithComplete:(void (^)(BOOL))complete
{
    if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        if (complete) {
            complete(NO);
        }
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager]
         uploadPatrolPictureToAliyunOSS:needUploadPic
         complete:^(BOOL isError, NSArray* uploadPictures) {
             [self pictureCompleteHandleWithNotice:notice needUploadPic:needUploadPic uploadedPic:uploadedPic error:isError WithComplete:^(BOOL success) {
                 if (complete) {
                     complete(success);
                 }
             }];
         }];
    });
}

- (void)pictureCompleteHandleWithNotice:(YWNotice *)notice needUploadPic:(NSArray *)needUploadPic uploadedPic:(NSArray *)uploadedPic error:(BOOL)isError WithComplete:(void (^)(BOOL))complete{
    if (!isError) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {if (complete) {complete(NO);}return;}
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:@(notice.noticeId)?:@"" forKey:@"id"];
        [params setValue:notice.title?:@"" forKey:@"title"];
        [params setValue:notice.content?:@"" forKey:@"content"];
        
//        [departments enumerateObjectsUsingBlock:^(NSObject *  _Nonnull departmentId, NSUInteger idx, BOOL * _Nonnull stop) {
//            [params setValue:departmentId?:@"" forKey:[NSString stringWithFormat:@"departmentReceivers[%lu].departmentId",(unsigned long)idx]];
//        }];
        NSMutableArray * totalPictures = [NSMutableArray array];
        [totalPictures addObjectsFromArray:needUploadPic];
        [totalPictures addObjectsFromArray:uploadedPic];
        [totalPictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull pic, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setObject:pic.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].url", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].thumbnailUrl", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].previewUrl", (unsigned long)idx]];
        }];
        YWLog(@"%@",params);
        
        [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getNoticeUrl] params:params success:^(NSHTTPURLResponse *response, id json) {
            // 更新数据库
            notice.imagesList = totalPictures;
            if (totalPictures.count==0) {
                [[YWNoticeManager shareManager] deletePictureOfNoticeWithNoticeId:notice.noticeId];
            }
            [[YWNoticeManager shareManager] updateNoticeWithNoticeArray:@[notice]];
            
            //成功刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshModifyYWNoticeNotification object:nil];
            if (complete) {
                complete(YES);
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyFailed", nil)];
            }
            if (complete) {
                complete(NO);
            }
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        }];
    }else{
        if (complete) {
            complete(NO);
        }
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
    }
}

- (void)requestDeleteNotice:(NSInteger)noticeId complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getNoticeUrl],(long)noticeId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        BOOL success = [[YWNoticeManager shareManager] deleteNoticeWithNoticeId:noticeId];
        if (success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteYWNoticeNotification object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

@end
